package com.project.servlet;

import com.project.bean.EmployeeBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        EmployeeBean em = new EmployeeBean();
        this.fullBean(req,em);

        resp.getWriter().print(em);
    }

    private void fullBean(HttpServletRequest req,Object beanObj){
        //得到客户端提交表单数据的名称集合
        Enumeration<String> em = req.getParameterNames();
        while(em.hasMoreElements()){//判断是否有下一个元素
            try {
                String formName = em.nextElement();//取出下一个元素

                //根据表单名，得到表单值
                String value = req.getParameter(formName);
                //根据表单名，得到属性对象
                Field field = beanObj.getClass().getDeclaredField(formName);
                field.setAccessible(true);
                //将实体对象的属性，赋值为value
                if(field.getType() == String.class) {//字符串
                    field.set(beanObj, value);
                }
                else if(field.getType() == int.class || field.getType() == Integer.class){//整型
                    field.set(beanObj,Integer.parseInt(value));
                }
                else if(field.getType() == double.class || field.getType() == Double.class){//浮点型
                    field.set(beanObj,Double.parseDouble(value));
                }
                else if(field.getType() == LocalDate.class){//日期型
                    field.set(beanObj,LocalDate.parse(value));
                }
                else if(field.getType() == String[].class){//字符串数组
                    field.set(beanObj,req.getParameterValues(formName));
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
